<template>
	<view>
		<view style="background-color: #D3D3D3;">
		<uni-search-bar placeholder="请输入城市名"  v-model="keyword" @blur="closeKeywords" @input="searchTips"  @confirm="search"></uni-search-bar>
		</view>
		<ul>
	  <li @click="search" v-if="showKeywords" v-for="(item,index) in tips" :key="item.id" style="padding: 10rpx 0rpx;">{{ item.name }}</li>
		  </ul>
  <view>
   
    <map 
      :longitude="longitude" 
      :latitude="latitude" 
      :markers="markers" 
      :show-location="true" 
      @click="mapClick"
      style="width: 750rpx; height: 1208rpx; display: block; box-sizing: border-box; left: 0rpx; top: 0rpx; position: relative;">
 </map>
    <view v-if="weatherInfo" style="position: absolute; left: 20rpx; bottom: 100rpx; background-color: white; padding: 20rpx; border-radius: 10rpx; box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);">
      <text>{{ weatherInfo.province }}</text>
      <text>,{{ weatherInfo.city }}</text>
      <text>,{{ weatherInfo.district }}</text><br>
      <text>温度：{{ weatherInfo.temp }}℃</text><br>
      <text>天气：{{ weatherInfo.weather }}</text>
      <button @click="closeWeatherInfo" style="margin-top: 10rpx;">关闭</button>
    </view>
  </view>
  </view>
</template>

<script>
	import amapFile from '@/AMapWX_SDK_V1.3.0/amap-wx.130.js';
export default {
  data() {
    return {
		showKeywords:false,
		 keyword: '', // 用户输入的关键词
		 tips: {},
      query: '',
      longitude: 0,
      latitude: 0,
      markers: [],
      weatherInfo: null
    };
  },
  
  onLoad(){
	  
  },
  created() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    this.getLocation();
    this.startLocationUpdates();
  },
  onShareAppMessage(res) {
    return {
      title: this.title,
      imageUrl: this.thumb
    };
  },
  onShareTimeline(res) {
    return {
      title: this.title,
      imageUrl: this.thumb
    };
  },
  watch: {
              keyword() {
                  this.tips = []
              },
          },
  methods: {
	  closeKeywords(){
		this.showKeywords=false  
		  
	  },
	 searchTips() {
		 this.showKeywords=true;
	                 this.myAmapFun = new amapFile.AMapWX({
	                     key: 'afe5c89d82feece4f601321a13bb165a' //微信小程序的key
	                 });
	                 const _this = this;
	                 // 发起搜索提示请求
	                 this.myAmapFun.getInputtips({
	                     keywords: this.keyword,
	                     city: '石家庄', //必须填写搜索的城市
	                     success(data) {
	                         console.log(data);
	                         if (data && data.tips) {
	                             _this.tips = data.tips;
	                             console.log(_this.tips);
	                         }
	                     },
	                 });
	             },
    getLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.longitude = res.longitude;
          this.latitude = res.latitude;
          this.markers = [{
            id: 1,
            longitude: res.longitude,
            latitude: res.latitude,
            title: '当前位置',
            width: 30,
            height: 30
          }];
        },
        fail: (err) => {
          console.error('获取位置失败：', err);
        }
      });
    },
    startLocationUpdates() {
      

      uni.onLocationChange((res) => {
        console.log('当前位置：', res);
        this.longitude = res.longitude;
        this.latitude = res.latitude;
        this.markers = [{
          id: 1,
          longitude: res.longitude,
          latitude: res.latitude,
          title: '当前位置',
          width: 30,
          height: 30
        }];
      });
    },
	
    search() {
      if (!this.keyword) {
        uni.showToast({
          title: '请输入城市名',
          icon: 'none'
        });
        return;
      }

      uni.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?address=${this.keyword}&key=C7XBZ-ZFP3N-I7VFT-SXU4U-IQMHV-2EFGF`,
        success: (res) => {
          if (res.data.status === 0 && res.data.result.location) {
            const location = res.data.result.location;
            this.longitude = location.lng;
            this.latitude = location.lat;
            this.markers = [{
              id: 2,
              longitude: this.longitude,
              latitude: this.latitude,
              title: this.keyword,
              width: 30,
              height: 30
            }];
          } else {
            uni.showToast({
              title: '未找到该城市',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error(err);
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    },
    mapClick(e) {
      const { longitude, latitude } = e.detail;
      this.getWeatherInfo(longitude, latitude);
    },
    getWeatherInfo(longitude, latitude) {
      uni.request({
        url: `https://devapi.qweather.com/v7/weather/now?location=${longitude},${latitude}&key=baf7fbe99ad449c893e017c5b27617ef`,
        success: (res) => {
          if (res.data && res.data.now) {
            this.getLocationInfo(longitude, latitude, (locationInfo) => {
              this.weatherInfo = {
                province: locationInfo.province,
                city: locationInfo.city,
                district: locationInfo.district,
                temp: res.data.now.temp,
                weather: res.data.now.text
              };
            });
          } else {
            this.weatherInfo = '未能获取天气信息';
          }
        },
        fail: (err) => {
          console.error(err);
          this.weatherInfo = '请求失败';
        }
      });
    },
    getLocationInfo(longitude, latitude, callback) {
      uni.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=C7XBZ-ZFP3N-I7VFT-SXU4U-IQMHV-2EFGF`,
        success: (res) => {
          if (res.data.status === 0 && res.data.result.address_component) {
            const addressComponent = res.data.result.address_component;
            const province = addressComponent.province || '未知省份';
            const city = addressComponent.city || addressComponent.province || '未知城市';
            const district = addressComponent.district || '未知区县';

            callback({
              province,
              city,
              district
            });
          } else {
            console.error('获取地理位置信息失败，状态码:', res.data.status, '响应数据:', res.data);
            callback({
              province: '未知省份',
              city: '未知城市',
              district: '未知区县'
            });
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          callback({
            province: '未知省份',
            city: '未知城市',
            district: '未知区县'
          });
        }
      });
    },
    closeWeatherInfo() {
      this.weatherInfo = null;
	  this.getLocation();
    }
  }
}
</script>

<style>

</style>
